package com.langfeiyes.pattern.interpret.demo1;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class ExpressionInterpretParser {


    private LinkedList<Expression> list = new LinkedList<>();

    private boolean isSymbol(String sy){
        return  "+".equals(sy) || "-".equals(sy) || "*".equals(sy)|| "/".equals(sy);
    }

    private Integer operation(Expression num1, Expression num2, String symbol){
        if("+".equals(symbol)){
            return new AddExpression(num1,num2).interpret();
        }else if("-".equals(symbol)){
            return new SubExpression(num1,num2).interpret();
        }else if("*".equals(symbol)){
            return new MulExpression(num1,num2).interpret();
        }else if("/".equals(symbol)){
            return new DivExpression(num1,num2).interpret();
        }

        return null;

    }
    public void parse(String express){
        String[] items = express.split(" ");
        for (String item : items) {
            if(!this.isSymbol(item)){
                list.addLast(new NumExpression(item));
                System.out.println("入栈参数：" + item);
            }else{
                System.out.println("运算符：" + item);
                Expression num1 = list.removeFirst();
                Expression num2 = list.removeFirst();
                Integer ret = this.operation(num1, num2, item);
                if(ret == null){
                    System.out.println("表达式解析异常，无法运算");
                    return;
                }
                this.list.push(new NumExpression(ret));
                System.out.println("运算结果再入栈：" + ret);
            }
        }

        if(list.size() == 1){
            System.out.println("表达式运算结果：" + list.removeFirst());
        }
    }
}
